﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

public class Player : MonoBehaviour
{
    bool death = false;

    Rigidbody2D bird_Rigidby;
    float force = 100f;
    Animator ani;
    Game game;
    GameObject clip;

    Vector3 InitPosition;

    public delegate void DeathNotify();
    public event DeathNotify OnDeath;

    public UnityAction<int> OnScore;

    //玩家移动速度
    private float speed = 5f;

    GameObject Bullettemplate;
    public GameObject BulletClip;
    float fireRate = 8f;
    bool isFlying = false;
    int HP_value = 1000;

    public int HP
    {
        set
        {
            HP_value = value;
        }
        get
        {
            return HP_value;
        }
    }

    // Start is called before the first frame update
    void Start()
    {
        Bullettemplate = Resources.Load("Prefabs/Bullet") as GameObject;
        ani = transform.GetChild(0).gameObject.GetComponent<Animator>();
        bird_Rigidby = gameObject.GetComponent<Rigidbody2D>();

        game = GameObject.Find("Canvas").GetComponent<Game>();
        InitPosition = transform.position;

        Idle();

    }


    float fireTimer = 0;

    // Update is called once per frame
    void Update()
    {
        if (death)
        {
            return;
        }

        if (!isFlying)
        {
            return;
        }
        fireTimer += Time.deltaTime;

        if (Input.GetButtonUp("Fire1"))
        {
            Fire();
        }

        Vector3 moveLenth = new Vector3(
                Input.GetAxis("Horizontal") * Time.deltaTime * speed, Input.GetAxis("Vertical") * Time.deltaTime * speed,
                0);
        transform.position += moveLenth;
    }

    public void Init()
    {
        transform.position = InitPosition;
        death = false;

        HP = 1000;

        Idle();
    }
    public void die()
    {
        death = true;

        if (this.OnDeath != null)
        {
            OnDeath();
        }
    }

    public void Idle()
    {
        bird_Rigidby.simulated = false;
        ani.SetTrigger("Idle");
        isFlying = false;
    }
    public void Fly()
    {

        bird_Rigidby.simulated = true;
        ani.SetTrigger("Fly");
        isFlying = true;
    }

    public void Fire()
    {
        if (fireTimer > 1f / fireRate)
        {
            Instantiate(Bullettemplate, gameObject.transform.position, transform.rotation, BulletClip.transform);
            fireTimer = 0;
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        //die();
        //print("peng!!!");
    }
    private void OnTriggerExit2D(Collider2D collision)
    {
        if (game.status != Game.Game_Status.Start)
        {
            return;
        }

        if (collision.gameObject.GetComponent<Bullet>().killer)
        {
            HP -= 100;
            if (HP <= 0)
            {
                die();
            }
        }
    }
}